<?php

namespace app\stock\controller\business;

use think\Controller;

class Source extends Controller
{
  public function _initialize()
  {
    parent::_initialize();
    $this->SourceModel = model('Business.Source');
  }

  // 列表
  public function index()
  {
    $data = $this->SourceModel->order('id', 'DESC')->select();

    $this->success('', '', $data);
  }

  // 添加
  public function add()
  {
    $name = $this->request->param('name', '', 'trim');

    // 添加校验器，校验不能为空，也不能重复名称
    $result = $this->SourceModel->save(['name' => $name]);

    if ($result) {
      $this->success('添加成功');
    } else {
      $this->error('添加失败');
    }
  }

  // 详情
  public function info()
  {
    $sourceid = $this->request->param('sourceid', 0, 'trim');

    $info = $this->SourceModel->find($sourceid);

    if (!$info) {
      $this->error('来源名称不存在');
    }

    $this->success('', '', $info);
  }

  // 编辑
  public function edit()
  {
    $name = $this->request->param('name', '', 'trim');

    $sourceid = $this->request->param('sourceid', 0, 'trim');

    $info = $this->SourceModel->find($sourceid);

    if (!$info) {
      $this->error('来源名称不存在');
    }

    // 添加校验器，校验不能为空，也不能重复名称
    $result = $this->SourceModel->where('id', $sourceid)->update(['name' => $name]);

    if ($result === false) {
      $this->error('更新失败');
    } else {
      $this->success('更新成功');
    }
  }

  // 删除
  public function del()
  {
    $sourceid = $this->request->param('sourceid', 0, 'trim');

    $info = $this->SourceModel->find($sourceid);

    if (!$info) {
      $this->error('来源名称不存在');
    }

    $result = $this->SourceModel->destroy($sourceid);

    if ($result === false) {
      $this->error('删除失败');
    } else {
      $this->success('删除成功');
    }
  }
}
